<?php
namespace Nawa\MedicalStudy\MedicalCenter;
/**
 * Medical Center Monitoring Visit.
 *
 * It represant a monotoring visit summary
 *
 * @author Xavier VILAIN
 * @package Nawa\MedicalStudy\MedicalCenter
 * @license #license-nawa#
 *
 * @property int	$msid				Id of the medical study
 * @property int	$mcid				Medical Center
 * @property int	$monitoringid		Monitoring Id (autoincremental)
 * @property string	$reference 			Custom Reference if needed
 * @property int	$type				Type of Checklist that should be use for
 * this monitoring
 * @property date	$monitoring_date	Date of the monitoring
 * @property int	$status				Status of the monitoring
 * @property float	$progress			% of progress
 * 
 * @method array partners()
 */
class Monitoring extends \Fox\Object {
	
	/**
	 * Link to Attached Partners
	 */
	const LINK_PARTNERS = 'partners';
	
	/**
	 * Link to Medical Center
	 */
	const LINK_MEDICAL_CENTER_PARTNER = 'medicalCenterPartner';
	
	/**
	 * Link to Surveys
	 */
	const LINK_SURVEYS = 'surveys';
		
	/**
	 * Documents
	 */
	const LINK_DOCUMENTS = 'documents';
	
	/**
	 * Unique id to handle correctly the MS breadcrumb
	 * @var string
	 */
	const BREADCRUMB_NODE = 'monitorings';
	
	/**
	 * Monitoring Default Statut
	 * @var string
	 */
	const STATUS_WIP = 2;
	
	/**
	 * Monitoring Default Statut
	 * @var string
	 */
	const STATUS_NEW = 1;
	
	/**
	 * Monitoring Validated Statut
	 * @var string
	 */
	const STATUS_VALIDATED = 5;	
	/**
	 * Monitoring Default Role
	 * @var string
	 */
	const ROLE_DEFAULT = 'PR';

	/**
	 * Monitoring Category of Document
	 * @var string
	 */
	const DOC_CATEGORY = 'mo';
	
	/**
	 * Monitoring defaumt Document type
	 * @var string
	 */
	const DOC_TYPE = 'mosi';
	
	/**
	 * Monitoring Label
	 * @return string
	 */
	public function label() {
		return $this->monitoringid;
	}
	
	/**
	 * 
	 * Check is the monitoring has been Validated
	 * @return bool
	 */
	public function isValitated($status = null) {
		if(empty($status)) {
			$status = $this->status ;
		}
		if($status == self::STATUS_VALIDATED) {
			return true;
		} else {
			return false;
		}
		 
	}
	
	/**
	 * Find all Monitored Patient
	 * @return array
	 */
	public function patients() {
		$patients = \Fox\Dao::finder(Patient::className())
			->follow(Patient::LINK_MONITORINGS)
				->where('msid = ? AND mcid = ? AND monitoring_date = ?',
						array($this->msid,$this->mcid,$this->monitoring_date))
				->find();
		return $patients;
	}
	
	/**
	 * 
	 * Monitoring Grid Partner Data
	 * Use this method as a short to retrieve all necessary 
	 * data for the Partner Grid
	 * 
	 * @return array
	 */
	public function partnersData() {
		$data = array();
		$handle = \Fox\Dao::infos(self::className())->handle();
		$query = $handle->createQueryBuilder();
		$query->select('t.msid','t.mcid','t.monitoringid','t.customerid','msp.role','msp.docid','c.name1','c.name2','c.docid AS base_docid')
				->from('ms_mc_monitoring_partners','t')
				->innerJoin('t','ms_partners','msp','msp.msid = t.msid AND msp.customerid = t.customerid')
				->innerJoin('t','customers','c','t.customerid = c.customerid');
		$fragments[] = new \Fox\Dao\SqlFragment('t.msid = ? AND t.mcid = ? AND t.monitoringid = ?',
						array($this->msid,$this->mcid,$this->monitoringid));
		$fragment = \Fox\Dao\SqlFragment::combine($fragments);
		$results = $fragment->pushIn($query)->execute()->fetchAll(\PDO::FETCH_ASSOC);
		foreach($results as $item)
		{
			$data[$item['customerid']] = $item;
		}
		return $data;
	}
	
	/**
	 * 
	 * Create Survey from Template
	 * This method is going to load the complete survey template
	 * and copy it to the current monitoring. It means everything
	 * sections,questions and answer will duplicated
	 * 
	 */
	public function createSurveyFromTemplate() {
		// Check that the template exists
		try {
			$surveyTemplate = new \Nawa\Survey($this->type);
		} catch(Fox\Object\Exception\NotExist $e) {
			throw new \Exception($e);
		}
		// Check that this survey does not already exist in 
		// the current monitoring
		// TODO in case of multiple survey for one monitoring
		
		// Create the survey object header
		$survey = new Monitoring\Survey();
		$survey->setFields(array(
			'msid' => $this->msid,
			'mcid' => $this->mcid,
			'monitoringid' => $this->monitoringid,
			'surveyid' => $surveyTemplate->surveyid,
			'version' => $surveyTemplate->versi,
	 		'uname' => \User::current(),
	 		'udate' => self::sqlDateTime(time()),
	 		'progress' => 0
		));
		$monitoringKeys = array('msid' => $this->msid,
								'mcid' => $this->mcid,
								'monitoringid' => $this->monitoringid,
								'surveyid' => $surveyTemplate->surveyid);
		$survey->create();
		/*
		// Comment for now has we only be pasting the survey  when monitoring has been set to validated
		$infos = \Fox\Dao::infos(self::className());
		$handle = $infos->handle();
		$handle->beginTransaction();
		// Add all question id's
		foreach($surveyTemplate->sections() as $section) {
			$handle->insert('ms_mc_monitoring_survey_sections',
							array_merge($monitoringKeys,
										array('sectionid' => $section->sectionid,'parentid' => $section->parentid,'progress' => 0)
								));
			foreach($section->questions() as $question) {
				$handle->insert('ms_mc_monitoring_survey_questions',
							array_merge($monitoringKeys,
										array('questionid' => $question->questionid,
											  'sectionid' => $section->sectionid,
											  'parentid' => $question->parentid,
											  'version' =>  $question->versi)
								));
			}
		}
		$handle->commit();
		*/
	}
	
	/**
	 * Find last uploaded document
	 * @return Monitoring\Document
	 */
	public function lastDocument() {
		$documents = \Fox\Dao::finder(Monitoring\Document::className())
			->where('msid = ? AND mcid = ? AND monitoringid = ?',
					array($this->msid,$this->mcid,$this->monitoringid))
			->orderBy('udate','DESC')
			->limit(1)
			->find();
		if(count($documents) == 1) {
			return $documents[0];
		} else {
			return null;
		}
	}
	
	/**
	 * (non-PHPdoc)
	 * @see Fox.Object::delete()
	 */
	public function delete() {
		// Remove Surveys
		foreach($this->surveys() as $survey) {
			$survey->delete();
		}
		// Remove Partners
		foreach($this->partners() as $partner) {
			$partner->delete();
		}
		// Remove Documents
		foreach($this->documents() as $document) {
			$document->delete();
		}
		parent::delete();
	}
}
\Fox\Dao::infos(Monitoring::className(),
new \Fox\Object\Info('ms_mc_monitorings', \Fox\Databases::DB_APP)
)->addAutoIncrementField('monitoringid');

// Link to Partners attached to the Medical Center Partner
\Fox\Object\Links::add(\Fox\Dao::link(Monitoring\Partner::className(),Monitoring\Partner::LINK_MEDICAL_CENTER_MONITORING)
->to(Monitoring::className(), Monitoring::LINK_PARTNERS)
->on('msid','mcid','monitoringid')
->versionFrom());

// Link to Survey attached to the Medical Center Partner
\Fox\Object\Links::add(\Fox\Dao::link(Monitoring\Survey::className(),Monitoring\Survey::LINK_MONITORING)
->to(Monitoring::className(), Monitoring::LINK_SURVEYS)
->on('msid','mcid','monitoringid')
->versionFrom());

// Link to Documents attached to the Medical Center Partner
\Fox\Object\Links::add(\Fox\Dao::link(Monitoring\Document::className(),Monitoring\Document::LINK_MONITORING)
->to(Monitoring::className(), Monitoring::LINK_DOCUMENTS)
->on('msid','mcid','monitoringid')
->versionFrom());

\Nawa\MedicalStudy\MedicalCenter::className();